//
//  LinkList.c
//  algorithmDemo
//
//  Created by 李文深 on 16/7/10.
//  Copyright © 2016年 30pay. All rights reserved.
//

#include "LinkList.h"
#include "FatalError.h"
#include <stdlib.h>

LinkList initLinkList() {
    
   LinkList l = (LinkList)malloc(sizeof(struct Node));
    
    if (l == NULL) {
        FatalError("初始化链表失败");
        return NULL;
    }
    
    l->next = NULL;
    
    return l;
}

Status appendListListElem(LinkList l, ElemType x) {
    
    LinkList p = l;
    
    while (p->next != NULL) {
        p = p->next;

    }
    
    LinkList tempCell = (LinkList)malloc(sizeof(struct Node));
    tempCell->data = x;
    tempCell->next = NULL;
    
    p->next = tempCell;
    
    return OK;
}

Status insertLinkListElem(LinkList l, ElemType x, int index) {
    
    if (index < 0 || index > (getLinkListLength(l)-1)) {
        FatalError("插入索引非法");
        return ERROR;
    }
    
    LinkList p = l;
    for (int i = 0; i < index; i++) {
        p = p->next;
    }
    
    LinkList tempCell = (LinkList)malloc(sizeof(struct Node));
    tempCell->data = x;
    
    tempCell->next = p->next;
    p->next = tempCell;
    
    return OK;
}


Status getLinkListElem(LinkList l, int index, ElemType *e) {
    
    if (index < 0 || index > (getLinkListLength(l)-1)) {
        FatalError("查找索引非法");
        return ERROR;
    }
    
    LinkList p = l->next;
    
    for (int i = 0; i < index; i++) {
        p = p->next;
    }
    
    *e = p->data;
    
    return OK;
}

int getLinkListLength(LinkList l) {
    
    int len = 0;
    LinkList p = l->next;
    while (p != NULL) {
        len++;
        p = p->next;
    }
    
    return len;
}

Status deleteLinkListElem(LinkList l,int index, ElemType *e) {
    
    if (index < 0 || index > (getLinkListLength(l)-1)) {
        FatalError("删除索引非法");
        return ERROR;
    }
    
    LinkList p = l;
    for (int i = 0; i < index; i++) {
        p = p->next;
    }
    
    LinkList q = p->next;
    *e = q->data;
    
    p->next = q->next;
    
    free(q);
    
    return OK;
}

void destroyLinkList(LinkList l) {
    LinkList p = l;
    LinkList q;
    while (p != NULL) {
        q = p->next;
        free(p);
        p = q;
    }
}

void printLinkList(LinkList l) {
    
    LinkList p = l->next;
    
    while (p != NULL) {
        printf("%d\n",p->data);
        p = p->next;
    }
    
}


void findMiddle(LinkList l, ElemType *e) {
    
    LinkList fast,slow;
    fast = slow = l;
    
    while (fast->next != NULL) {
        
        if(fast->next->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
        }else {
            fast = fast->next;
        }
    }
    
    *e = slow->data;
}


